//
//  PPHomeAlumAddImageController.m
//  pickpic
//
//  Created by 胡文广 on 2017/4/23.
//  Copyright © 2017年 MicroDream. All rights reserved.
//

#import "PPHomeAlumAddImageController.h"
#import "PPAlbumModel.h"
#import "PPAlbumAddImageCell.h"
#import "PPAlbumContentViewDataSource.h"
#import "DGBlockAlertView.h"
@interface PPHomeAlumAddImageController ()<UICollectionViewDelegate,UICollectionViewDataSource>
@property (nonatomic,strong) UICollectionView *mainCollectionView;
@property (nonatomic,strong) NSArray *albums;
@property (nonatomic,strong) UIImageView *line;
@property (nonatomic,assign) NSInteger selectItem;
@property (nonatomic,strong) PPAlbumContentViewDataSource *dataSource;
@end

@implementation PPHomeAlumAddImageController
static NSString *const ebookID = @"AlbumAddImageCell";
- (PPAlbumContentViewDataSource *)dataSource{
    if (!_dataSource) {
        _dataSource = [[PPAlbumContentViewDataSource alloc] init];
        _dataSource.privacy = @(PPAlbumPrivacyAll);
        _dataSource.permission = @(PPAlbumCommentEnabled);
        _dataSource.order = @(PPAlbumOrderDesc);
    }
    return _dataSource;
}
- (NSArray *)alums{
    
    if (!_albums) {
        _albums = [NSArray array];
    }
    return _albums;
}
- (void)popViewPreviousController{

    DGBlockAlertView *alertView = [DGBlockAlertView alertWithTitle:@"是否退出编辑？" message:nil cancelTitle:@"取消" cancelBlock:nil confirmTitle:@"退出" comfirmBlock:^{
        [self.navigationController popViewControllerAnimated:YES];
    }];
    
    [alertView show];
    
    
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = WHITE;
    self.selectItem = 0;

    
    [self setupBackItem];
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"完成" style:UIBarButtonItemStylePlain target:self action:@selector(saveAlbum)];
    
    
    
    self.albums = [PPAlbumModel where:@{@"deleted" : @(NO)} order:@{@"update" : @"desc"}];

    UILabel *headl = [[UILabel alloc] initWithFrame:CGRectMake(15, 0, self.view.width, 80)];
    headl.backgroundColor = WHITE;
    headl.text = @"保存至";
    headl.font = PPFONTSIZE(18.f);
    
    [self.view addSubview:headl];
    
    UIImageView *line = [[UIImageView alloc] initWithFrame:CGRectMake(15, CGRectGetMaxY(headl.frame), self.view.width-15, 0.5)];
    line.backgroundColor = [UIColor groupTableViewBackgroundColor];
    [self.view addSubview:line];
    self.line = line;
    
    [self creatCollectionView];
    
}
- (void)saveAlbum{
    
    PPAlbumModel *ablumM = self.albums[self.selectItem];
    
    [self getAlbumAuuid:ablumM.auuid];
    
    PPLog(@"---%@",ablumM.auuid);
    
    NSString *coverUUID = nil;
    
    if(_dataSource.coverUUID != nil) {
        coverUUID = _dataSource.coverUUID;
    } else {
        // 从images里找第一张图作为cover
        BOOL force = NO;
        if(ablumM.auuid != nil) {
            PPAlbumModel *album = [PPAlbumModel find:@{@"auuid": ablumM.auuid}];
            if(album.coverKey.length == 0 || album.coverHost.length == 0) {
                force = YES;
            }
        } else {
            force = YES;
        }
        
        if(force) {
            NSArray <PPAbstractArtwork *> *sortedImages = nil;
            if(_dataSource.order.integerValue == PPAlbumOrderAsc) {
                sortedImages = self.dataSource.images;
            } else {
                sortedImages = [self.dataSource.images.reverseObjectEnumerator allObjects];
            }
            coverUUID = sortedImages.firstObject.uuid;
        }
    }
    
        [[PPAlbumManager sharedInstance] offlineModifyAlbumWithAlbumUUID:ablumM.auuid insertedArtworks:_dataSource.insertedImages modifiedArtworks:_dataSource.modifiedImages deletedArtworks:_dataSource.deletedImages tags:_dataSource.tags title:_dataSource.title description:_dataSource.desc order:_dataSource.order permission:_dataSource.permission privacy:_dataSource.privacy privacyUserIDs:_dataSource.privacyUserIDs coverUUID:coverUUID];

    [self.navigationController popViewControllerAnimated:YES];

}
//创建collectionView
-(void)creatCollectionView{
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    //该方法也可以设置itemSize
    layout.itemSize =CGSizeMake(SCREEN_WIDTH/4,93);
    // 设置最小行间距
    layout.minimumLineSpacing = 0;
    // 设置垂直间距
    layout.minimumInteritemSpacing = 0;
    //2.初始化collectionView
    _mainCollectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(self.line.frame)+5, self.view.width, self.view.frame.size.height- CGRectGetMaxY(self.line.frame)) collectionViewLayout:layout];
    [self.view addSubview:_mainCollectionView];
    
    [_mainCollectionView registerNib:[UINib nibWithNibName:NSStringFromClass([PPAlbumAddImageCell class]) bundle:nil] forCellWithReuseIdentifier:ebookID];
    
    _mainCollectionView.delegate = self;
    _mainCollectionView.dataSource = self;
    
    _mainCollectionView.backgroundColor = WHITE;
    
}

//每个section的item个数
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.albums.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    PPAlbumAddImageCell *cell = (PPAlbumAddImageCell *)[collectionView dequeueReusableCellWithReuseIdentifier:ebookID forIndexPath:indexPath];
    PPAlbumModel *album = self.albums[indexPath.row];
    if (self.selectItem == indexPath.row) {
        cell.coverLabel.text = [NSString stringWithFormat:@"+%zd",self.photos.count];
    }else{
        cell.coverLabel.text = @"";;
    }
    cell.coverLabel.textColor = WHITE;
    [cell.coverImageView setCoverImageWithAlbum:album];
    
//    PPPhoto *p = self.smallPhotos[indexPath.item];
//    [cell.img sd_setImageWithURL:[NSURL URLWithString:p.bigImgUrl]];
    return cell;
}
//- (void)setAlbum:(PPAlbumModel *)album {
//    _album = album;
//    
//    _titleLabel.text = album.title;
//    
//    NSArray <PPAlbumImageModel *> *images = [PPAlbumImageModel where:@{@"auuid": album.auuid, @"deleted": @(NO)}];
//    _countLabel.text = [NSString stringWithFormat:@"%li张", images.count];
//    
//    [_coverView setCoverImageWithAlbum:album];
//    
//    _updateLabel.text = [[NSDate dateWithTimeIntervalSince1970:album.update.doubleValue] timeAgoForTimeline];
//}
//点击item方法
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    
    self.selectItem = indexPath.item;
    
    [self.mainCollectionView reloadData];
}
- (void)getAlbumAuuid:(NSString *)auuid {
    if(auuid == nil) {
        return;
    }
    
    PPAlbumModel *album = [PPAlbumModel find:@{@"auuid" : auuid}];
    
    self.dataSource.title = album.title;
    self.dataSource.desc = album.desc;
    self.dataSource.privacy = album.privacy;
    self.dataSource.permission = album.permission;
    self.dataSource.order = album.order;
    
    
    
    for (UIImage *img in self.photos) {
        
        PPAbstractArtwork *artwork = [[PPAbstractArtwork alloc] init];
        artwork.uuid = [NSString uuid];
        artwork.image = [img fixOrientation];
        artwork.created = YES;
        
        [self.dataSource.images addObject:artwork];
        [self.dataSource.insertedImages addObject:artwork];
    }
    
    
    NSArray *privacyUserIDs = [album.privacyUserIDs componentsSeparatedByString:@","];
    
    for(NSInteger index = 0; index < privacyUserIDs.count; index++) {
        NSString *privacyUserID = [privacyUserIDs validStringAtIndex:index];
        
        if(privacyUserID.length > 0) {
            [_dataSource.privacyUserIDs addSafeObject:privacyUserID];
        }
    }
    
    NSArray <PPAlbumImageModel *> *images = [PPAlbumImageModel where:@{@"auuid" : auuid, @"deleted" : @(NO)}];
    
    NSArray <PPAlbumTagModel *> *tags = [PPAlbumTagModel where:@{@"auuid" : auuid}];
    
    [images enumerateObjectsUsingBlock:^(PPAlbumImageModel *_Nonnull obj, NSUInteger idx, BOOL *_Nonnull stop) {
        PPAbstractArtwork *artwork = obj.artwork;
        [_dataSource.images addObject:artwork];
    }];
    
    [tags enumerateObjectsUsingBlock:^(PPAlbumTagModel *_Nonnull obj, NSUInteger idx, BOOL *_Nonnull stop) {
        PPAlbumTagElement *tag = [[PPAlbumTagElement alloc] init];
        tag.tagID = obj.tagID;
        tag.name = obj.name;
        [_dataSource.tags addObject:tag];
    }];
}


@end
